package com.bilibili.juc.cf.one;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/*
当发生异常时，handler也会执行，只不过CompletableFuture.supplyAsync 传递过来的参数为null
 */
public class FutureHandler2Test {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> orgFuture = CompletableFuture.supplyAsync(
                ()->{
                    System.out.println("supplyAsync 当前线程名称：" + Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    int count = RandomUtil.randomInt(1, 10);
                    System.out.println("随机数为: " + count);
                    if (count < 7){
                        throw new RuntimeException("第一个任务抛出了异常");
                    }
                    return "捡田螺的小男孩";
                }
        );

        CompletableFuture<String> handler1Future = orgFuture.handle((a, throwable) -> {
            System.out.println("handle1 当前线程名称：" + Thread.currentThread().getName());
            System.out.println("上个任务执行完啦，还把 \"" + a + "\" 传过来");
            if ("捡田螺的小男孩".equals(a)) {
                System.out.println("111");
                return a+"==>>handler1关注了";
            }
            System.out.println("222");
            return a+"==>>handler1再考虑一下";
        });
        CompletableFuture<String> handler2Future = handler1Future.handle((a, throwable) -> {
            System.out.println("handle2 当前线程名称：" + Thread.currentThread().getName());
            System.out.println("上个任务执行完啦，还把 \"" + a + "\" 传过来");
            if ("捡田螺的小男孩".equals(a)) {
                System.out.println("333");
                return a+"==>>handler2关注了";
            }
            System.out.println("444");
            return a+"==>>handler2再考虑一下";
        });

        System.out.println("handler1Future结果："+handler1Future.get());
        System.out.println("handler2Future结果："+handler2Future.get());
        for (int i = 0 ; i < 5;i++){
            System.out.println(" 主程序正在执行其它的任务"+i);
            TimeUnit.SECONDS.sleep(1);
        }
    }
}
/*
supplyAsync 当前线程名称：ForkJoinPool.commonPool-worker-1
随机数为: 6
handle1 当前线程名称：ForkJoinPool.commonPool-worker-1
上个任务执行完啦，还把 "null" 传过来
222
handle2 当前线程名称：ForkJoinPool.commonPool-worker-1
上个任务执行完啦，还把 "null==>>handler1再考虑一下" 传过来
444
handler1Future结果：null==>>handler1再考虑一下
handler2Future结果：null==>>handler1再考虑一下==>>handler2再考虑一下
 */
